﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using RoadFlow.Utility;

namespace RoadFlow.Mvc.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class MenuController : Controller
    {
        [Validate]
        public IActionResult Index()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        public IActionResult Empty()
        {
            return View();
        }

        [Validate]
        public IActionResult Tree()
        {
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid");
            return View();
        }

        [Validate]
        public IActionResult Body()
        {
            string menuId = Request.Querys("menuid");
            string parentId = Request.Querys("parentid");
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["queryString"] = Request.UrlQuery();

            Business.Menu menu = new Business.Menu();
            Business.AppLibrary appLibrary = new Business.AppLibrary();
            Model.Menu menuModel = null;
            string appType = string.Empty;
            if (menuId.IsGuid(out Guid mid))
            {
                menuModel = menu.Get(mid);
                if (null != menuModel && menuModel.AppLibraryId.HasValue)
                {
                    var applibraryModel = appLibrary.Get(menuModel.AppLibraryId.Value);
                    if (null != applibraryModel)
                    {
                        appType = applibraryModel.Type.ToString();
                    }
                }
            }
            if (null == menuModel)
            {
                menuModel = new Model.Menu()
                {
                    Id = Guid.NewGuid(),
                    ParentId = parentId.ToGuid(),
                    Sort = menu.GetMaxSort(parentId.ToGuid())
                };
            }

            ViewData["typeOptions"] = appLibrary.GetTypeOptions(appType);
            return View(menuModel);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string Save(Model.Menu menuModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.Menu menu = new Business.Menu();
            string menuid = Request.Querys("menuid");
            if (menuid.IsGuid(out Guid mid))
            {
                var oldModel = menu.Get(mid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                menu.Update(menuModel);
                Business.Log.Add("修改了菜单-" + menuModel.Title, "", Business.Log.Type.系统管理, oldJSON, menuModel.ToString());
            }
            else
            {
                menu.Add(menuModel);
                Business.Log.Add("添加了菜单-" + menuModel.Title, menuModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string Delete()
        {
            string menuid = Request.Querys("menuid");
            if (!menuid.IsGuid(out Guid mid))
            {
                return "ID错误";
            }
            Business.Menu menu = new Business.Menu();
            var menuModel = menu.Get(mid);
            if (null == menuModel)
            {
                return "未找到要删除的菜单";
            }
            menu.Delete(new Model.Menu[] { menuModel });
            Business.Log.Add("删除了菜单-" + menuModel.Title, menuModel.ToString(), Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate]
        public IActionResult Sort()
        {
            Business.Menu menu = new Business.Menu();
            string parentid = Request.Querys("parentid");
            var childs = menu.GetChilds(parentid.ToGuid());
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["parentId"] = parentid;
            return View(childs);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveSort()
        {
            Business.Menu menu = new Business.Menu();
            string sorts = Request.Forms("sort");
            string parentid = Request.Querys("parentid");
            var childs = menu.GetChilds(parentid.ToGuid());
            int i = 0;
            foreach (string sort in sorts.Split(','))
            {
                if (sort.IsGuid(out Guid mid))
                {
                    var menuModel = childs.Find(p => p.Id == mid);
                    if (null != menuModel)
                    {
                        menuModel.Sort = i += 5;
                    }
                }
            }
            menu.Update(childs.ToArray());
            return "排序成功!";
        }

        [Validate]
        public string Tree1()
        {
            Business.Menu menu = new Business.Menu();
            var appDt = menu.GetMenuAppDataTable();
            if (appDt.Rows.Count == 0)
            {
                return "[]";
            }
            var root = appDt.Select("ParentId='" + Guid.Empty.ToString() + "'");
            if (root.Length == 0)
            {
                return "[]";
            }
            DataRow rootDr = root[0];
            var apps = appDt.Select("ParentId='" + rootDr["Id"].ToString() + "'");
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JObject rootJObject = new Newtonsoft.Json.Linq.JObject()
            {
                { "id" , rootDr["Id"].ToString()},
                { "parentID", Guid.Empty},
                { "title", rootDr["Title"].ToString()},
                { "ico", rootDr["Ico"].ToString()},
                { "link", rootDr["Address"].ToString()},
                { "type", 0},
                { "model", rootDr["OpenMode"].ToString()},
                { "width", rootDr["Width"].ToString()},
                { "height", rootDr["Height"].ToString()},
                { "hasChilds", apps.Length}
            };
            jArray.Add(rootJObject);
            Newtonsoft.Json.Linq.JArray jArray1 = new Newtonsoft.Json.Linq.JArray();
            foreach (var app in apps)
            {
                Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject()
                {
                    { "id" , app["Id"].ToString()},
                    { "parentID", rootDr["Id"].ToString()},
                    { "title", app["Title"].ToString()},
                    { "ico", app["Ico"].ToString()},
                    { "link", app["Address"].ToString()},
                    { "type", 0},
                    { "model", app["OpenMode"].ToString()},
                    { "width", app["Width"].ToString()},
                    { "height", app["Height"].ToString()},
                    { "hasChilds", appDt.Select("ParentId='" + app["Id"].ToString() + "'").Length}
                };
                jArray1.Add(jObject1);
            }
            rootJObject.Add("childs", jArray1);
            return jArray.ToString();
        }

        [Validate]
        public string TreeRefresh()
        {
            string refreshid = Request.Querys("refreshid");
            Business.Menu menu = new Business.Menu();
            var appDt = menu.GetMenuAppDataTable();
            if (appDt.Rows.Count == 0)
            {
                return "[]";
            }
            var apps = appDt.Select("ParentId='" + refreshid + "'");
            if (apps.Length == 0)
            {
                return "[]";
            }
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var app in apps)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                {
                    { "id" , app["Id"].ToString()},
                    { "parentID", refreshid},
                    { "title", app["Title"].ToString()},
                    { "ico", app["Ico"].ToString()},
                    { "link", app["Address"].ToString()},
                    { "type", 0},
                    { "model", app["OpenMode"].ToString()},
                    { "width", app["Width"].ToString()},
                    { "height", app["Height"].ToString()},
                    { "hasChilds", appDt.Select("ParentId='" + app["Id"].ToString() + "'").Length}
                };
                jArray.Add(jObject);
            }
            return jArray.ToString();
        }
    }
}